
object CSVParser {
  def parseLine(ln: String) = {
    def loop(i: Int): List[(Int, Int)] = {
      if (i >= ln.length) {
        List()
      } else {
        def parse(i: Int, ch: Char): Int =
          if (i == ln.length || ln(i) == ch) i else parse(i + 1, ch)
        ln(i) match {
          case '\"' =>
            val j = parse(i + 1, '\"')
            assert(ln(j + 1) == ',')
            (i + 1, j)::loop(j + 2)
          case _ =>
            val j = parse(i, ',')
            (i, j)::loop(j + 1)
        }
      }
    }
    loop(0)
  }
}

val line = """apple,,grape,"yuzu,biwa",lemon"""

CSVParser.parseLine(line).foreach { rng =>
  val (s, e) = rng
  println("%d:%d\t%s".format(s, e, line.slice(s, e)))
}
